package com.hsy.baoinbao.modules.order.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.deparse.dpframe.ui.adapter.DPBaseAdapter;
import com.deparse.dpframe.utils.DPGsonUtil;
import com.deparse.dpframe.utils.DPHttpUtil;
import com.deparse.dpframe.utils.DPLogUtil;
import com.hsy.baoinbao.R;
import com.hsy.baoinbao.common.Consts;
import com.hsy.baoinbao.modules.common.CommonBaseActivityWithSimpleActionBar;
import com.hsy.baoinbao.modules.main.ui.activity.MainActivity;
import com.hsy.baoinbao.modules.my.gsondata.PersonalData;
import com.hsy.baoinbao.modules.order.adapter.GoodsAllAdapter;
import com.hsy.baoinbao.modules.order.gsondata.ReceivingOrderDetail;
import com.hsy.baoinbao.modules.order.view.EditTextExt;
import com.hsy.baoinbao.utils.CommonUtils;
import com.hsy.baoinbao.utils.HttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/3/27.
 */
public class DetailReceivingActivity extends CommonBaseActivityWithSimpleActionBar {
    private ExpandableListView receive_expand_list;
    private AdapterListView detailGoodsAdapter;
    private ReceivingOrderDetail.Result listData;
    private TextView address, tel, cancel, success, name_merchant, is_recycling_man_pay;
    private String orderId;
    private Intent intent;
    private LinearLayout finish;
    private TextView totalPriceTextView;
    private AlertDialog builder;
    private DPHttpUtil.HttpCallback httpCallBack = new DPHttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, String response) {
            if (0 == what) {
                listData = DPGsonUtil.fromJson(response, ReceivingOrderDetail.Result.class);
                DPLogUtil.d(listData.toString());

                address.setText(listData.getAddress());
                tel.setText(listData.getTel());

                name_merchant.setText(listData.getName_merchant());
                if ("1".equals(String.valueOf(listData.getIs_recycling_man_pay()))) {

                    is_recycling_man_pay.setText("现金");
                } else if ("2".equals(String.valueOf(listData.getIs_recycling_man_pay()))) {

                    is_recycling_man_pay.setText("余额");
                }


                int status = listData.getStatus();
                if (2 == status) {
                    finish.setVisibility(View.GONE);
                } else if (1 == status) {
                    finish.setVisibility(View.VISIBLE);
                } else if (3 == status) {
                    finish.setVisibility(View.GONE);
                }
                detailGoodsAdapter = new AdapterListView(DetailReceivingActivity.this, listData);
                receive_expand_list.setAdapter(detailGoodsAdapter);
                CommonUtils.hideProgressDialog();
            } else if (1 == what) {
                showToast(R.string.txt_canceled_successfully);
                CommonUtils.hideProgressDialog();
                builder.dismiss();
                if (!fromNotification) {
                    startActivityWithTaskCleared(MainActivity.class, Consts.JUMP_TO_CYCLE_CANCEL);
                } else {
                    startActivityWithTaskCleared(MainActivity.class);
                }
            } else if (100 == what) {
                showToast(R.string.txt_committed_successfully);
                CommonUtils.hideProgressDialog();
                if (!fromNotification) {
                    startActivityWithTaskCleared(MainActivity.class, Consts.JUMP_TO_CYCLE_DONE);
                } else {
                    startActivityWithTaskCleared(MainActivity.class);
                }
            }

        }

        @Override
        public void onError(int what, int type, VolleyError error) {
            if (1 == what) {
                CommonUtils.hideProgressDialog();
            }
            if (0 == what) {
                CommonUtils.hideProgressDialog();
            }
            if (100 == what) {
                CommonUtils.hideProgressDialog();
            }
        }
    };
    private boolean fromNotification = false;

    private boolean checkNull() {
        if (totalPriceTextView.getText().toString().equals("0.00元")) {
            showToast("请输入数量");
            return false;
        }
        return true;
    }

    @Override
    public boolean onActionBarLeftButtonClicked(ImageButton leftButton) {
        if (!fromNotification) {
            return false;
        } else {
            startActivityWithTaskCleared(MainActivity.class);
            return true;
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (!fromNotification) {
            return super.dispatchKeyEvent(event);
        } else {
            startActivityWithTaskCleared(MainActivity.class);
            return true;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail_receiving);
        setTitle("订单详情");
        receive_expand_list = F(R.id.receive_expand_list);
        receive_expand_list.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {

            @Override
            public void onGroupCollapse(int groupPosition) {
                InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getWindow().getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }
            }
        });

        receive_expand_list.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {

            @Override
            public void onGroupExpand(int groupPosition) {
                InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getWindow().getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }
            }
        });

        receive_expand_list.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }

        });

        address = F(R.id.address);
        tel = F(R.id.tel);
        name_merchant = F(R.id.name_merchant);
        is_recycling_man_pay = F(R.id.is_recycling_man_pay);


        finish = F(R.id.finish);
        cancel = F(R.id.cancel);
        success = F(R.id.success);

        totalPriceTextView = F(R.id.total_price);

        intent = getIntent();
        orderId = intent.getStringExtra("id");
        fromNotification = intent.getBooleanExtra("fromNotification", false);
        CommonUtils.showProgressDialog(this);
        DPLogUtil.d("getIntent" + orderId);
        Map<String, String> data = new HashMap<>();
        data.put("token", CommonUtils.getToken(DetailReceivingActivity.this));
        data.put("id", orderId);
        HttpUtil.httpPostWithParams(DetailReceivingActivity.this, 0, Consts.API_FAIL_RECYCLE_ORDER, data, httpCallBack);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });
        success.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkNull()) {
                    CommonUtils.showProgressDialog(DetailReceivingActivity.this);
                    Map<String, String> data = new HashMap<>();
                    data.put("token", CommonUtils.getToken(DetailReceivingActivity.this));
                    data.put("id", orderId);
                    data.put("data", DPGsonUtil.toJson(listData));
                    HttpUtil.httpPostWithParams(DetailReceivingActivity.this, 100, Consts.API_COMMIT_RECYCLE_ORDER, data, httpCallBack);
                }
            }
        });
    }

    public void showDialog() {
        RadioGroup reason_parent;
        final RadioButton first_reason, second_reason, third_reason;
        final EditText other_reason_edit;
        TextView success, cancel;
        builder = new AlertDialog.Builder(this).create();
        LayoutInflater inflater = LayoutInflater.from(this);
        //获取相关的布局
        View layout = inflater.inflate(R.layout.dialog_view, (ViewGroup) findViewById(R.id.dialog_parent));

        reason_parent = (RadioGroup) layout.findViewById(R.id.reason_parent);
        other_reason_edit = (EditText) layout.findViewById(R.id.other_reason_edit);
        success = (TextView) layout.findViewById(R.id.success);
        cancel = (TextView) layout.findViewById(R.id.cancel);
        first_reason = (RadioButton) layout.findViewById(R.id.first_reason);
        second_reason = (RadioButton) layout.findViewById(R.id.second_reason);
        third_reason = (RadioButton) layout.findViewById(R.id.third_reason);
        other_reason_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                first_reason.setChecked(false);
                second_reason.setChecked(false);
                third_reason.setChecked(false);
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
        success.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtils.showProgressDialog(DetailReceivingActivity.this);
                Map<String, String> data = new HashMap<>();
                data.put("token", CommonUtils.getToken(DetailReceivingActivity.this));
                data.put("id", orderId);
                data.put("reason", other_reason_edit.getText().toString());
                DPLogUtil.d("reason" + other_reason_edit.getText().toString());
                DPLogUtil.d("id" + orderId);
                HttpUtil.httpPostWithParams(DetailReceivingActivity.this, 1, Consts.API_CANCEL, data, httpCallBack);

            }
        });
        reason_parent.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.first_reason) {
                    other_reason_edit.setText("联系不上客户");
                } else if (checkedId == R.id.second_reason) {
                    other_reason_edit.setText("联系不上负责人");
                } else if (checkedId == R.id.third_reason) {
                    other_reason_edit.setText("订单被取消");
                }
            }
        });
//        builder.setView(layout);
        builder.show();
        builder.setCancelable(false);
        builder.getWindow().setContentView(layout);
        builder.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    }

    public void countTotalPrice() {
        float p = 0;
        for (ReceivingOrderDetail.Goods goods : listData.getGoods()) {
            for (ReceivingOrderDetail.Children child : goods.getChildren()) {
                try {
                    p += (child.getQty() * Float.valueOf(child.getPrice()));
                } catch (Exception e) {
                    continue;
                }
            }
        }
        totalPriceTextView.setText(String.format("%.2f元", p));
    }

    public class AdapterListView extends BaseExpandableListAdapter {
        private List<ReceivingOrderDetail.Goods> listData;
        private LayoutInflater mInflater;
        private int status;

        public AdapterListView(Context context, ReceivingOrderDetail.Result src) {
            status = src.getStatus();
            listData = src.getGoods();
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            countTotalPrice();
        }

        //得到子item需要关联的数据
        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return (listData.get(childPosition).getChildren());
        }

        //得到子item的ID
        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        //设置子item的组件
        @Override
        public View getChildView(final int groupPosition, final int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
            ChildViewHolder childViewHolder = null;

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_detail_receiving_into_child1, null);

                childViewHolder = new ChildViewHolder();
                childViewHolder.init(convertView, status);
            } else {
                childViewHolder = (ChildViewHolder) convertView.getTag();
            }
            childViewHolder.setData(listData.get(groupPosition).getChildren().get(childPosition));
            return convertView;
        }

        //获取当前父item下的子item的个数
        @Override
        public int getChildrenCount(int groupPosition) {
            return listData.get(groupPosition).getChildren().size();
        }

        //获取当前父item的数据
        @Override
        public Object getGroup(int groupPosition) {
            return listData.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return listData.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        //设置父item组件
        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            convertView = mInflater.inflate(R.layout.item_detail_receiving_group, null);
            TextView firstName = (TextView) convertView.findViewById(R.id.groupName);
            firstName.setText(listData.get(groupPosition).getName());
            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public class ChildViewHolder implements View.OnClickListener {

            public ReceivingOrderDetail.Children src;

            public TextView nameTextView;
            public TextView priceTextView;
            public ImageView increaceImageView;
            public EditTextExt valueEditTextExt;
            public ImageView decreaceImageView;
            public TextView unitTextView;
            public TextView showTextView;
            public LinearLayout editAreaLinearLayout;

            public ChildViewHolder() {

            }

            public void init(View convertView, int status) {
                convertView.setTag(this);

                nameTextView = (TextView) convertView.findViewById(R.id.name);
                priceTextView = (TextView) convertView.findViewById(R.id.price);
                increaceImageView = (ImageView) convertView.findViewById(R.id.increace);
                valueEditTextExt = (EditTextExt) convertView.findViewById(R.id.value);
                decreaceImageView = (ImageView) convertView.findViewById(R.id.decreace);
                unitTextView = (TextView) convertView.findViewById(R.id.unit);
                showTextView = (TextView) convertView.findViewById(R.id.show);
                editAreaLinearLayout = (LinearLayout) convertView.findViewById(R.id.edit_area);

                if (2 == status || 3 == status) {
                    showTextView.setVisibility(View.VISIBLE);
                    editAreaLinearLayout.setVisibility(View.GONE);
                } else {
                    showTextView.setVisibility(View.GONE);
                    editAreaLinearLayout.setVisibility(View.VISIBLE);
                }

                valueEditTextExt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (hasFocus) {
                            valueEditTextExt.setSelection(valueEditTextExt.getText().length());
                            valueEditTextExt.setCursorVisible(true);
                        } else {
                            valueEditTextExt.setCursorVisible(false);
                        }
                    }
                });

                valueEditTextExt.setOnTextChangedListener(new EditTextExt.OnTextChangedListener() {
                    @Override
                    public void beforeTextChanged(EditTextExt editTextExt, CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void afterTextChanged(EditTextExt editTextExt, Editable s) {
                        if (null != src) {
                            if ("".equals(editTextExt.getText().toString())) {
                                src.setQty(0);
                            } else {
                                src.setQty(Long.parseLong(editTextExt.getText().toString()));
                            }
                            countTotalPrice();
                        }
                    }

                    @Override
                    public void onTextChanged(EditTextExt editTextExt, CharSequence s, int start, int count) {

                    }
                });

                valueEditTextExt.setText("0");
                valueEditTextExt.setSelection(1);

                increaceImageView.setOnClickListener(this);
                decreaceImageView.setOnClickListener(this);
            }

            public void setData(ReceivingOrderDetail.Children src) {
                if (null == src) {
                    DPLogUtil.e("src = null.");
                    return;
                }
                this.src = src;
                this.nameTextView.setText(src.getName());
                this.unitTextView.setText(src.getUnit());
                this.priceTextView.setText(src.getPrice() + "元" + "/" + src.getUnit());

                this.valueEditTextExt.setText(String.valueOf(src.getQty()));
                this.showTextView.setText(String.valueOf(src.getQty()));
            }

            @Override
            public void onClick(View v) {
                long n = 0;
                try {
                    n = Long.parseLong(valueEditTextExt.getText().toString());
                } catch (Exception e) {

                }
                if (v.getId() == R.id.increace) {
                    if (n < 1000) {
                        n++;
                    }
                } else if (v.getId() == R.id.decreace) {
                    if (n > 0) {
                        n--;
                    }
                }
                valueEditTextExt.setText(String.valueOf(n));
                valueEditTextExt.requestFocus();
            }
        }
    }

}
